package com.demo.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 异常信息收集
 * @author gy
 * @date 2022/6/15
 */
@Component
@Aspect
public class ExceptionAspect {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAspect.class);

    @Pointcut("execution(* com.demo.service..*.*(..))")
    private void webLog(){

    }

    @AfterThrowing(value = "webLog()",throwing = "e")
    public void afterThrowing(JoinPoint jp,Throwable e){
        // 获取目标对象
        Object target = jp.getTarget();
        Class<?> clz = target.getClass();

        // 获取目标方法
        MethodSignature m = (MethodSignature)jp.getSignature();
        Method method = m.getMethod();

        // 记录日志
        logger.error("在["+clz+"]类["+method+"]方法抛出["+e+"]异常");
    }
}
